import ChatSocket from '@/common/chat'
import store from '@/store'
import request from '@/axios'
import Common from '@/common/global'
export default ({
  namespaced:true,
  state: {
    Chat:null,    
    Socket:null,     //一个websocket服务
    NaviState:1,    //1:消息 2:联系人 3:群聊 4:星球
    ContentState:0, //0:空状态 1:消息 2:联系人 3:好友资料

    DrawerState:0,    //0:无 1:好友资料
    DrawerData:null, //抽屉数据
    
    ContentTitle:null, //内容标题


    Chatlist:[] ,//聊天列表
    ChatNow:null, //正在聊天的对象
    ChatContentNow:[],//正在聊天对象的内容
  },
  getters: {

  },
  mutations: {
    //初始化websocket服务
     SETCHAT:(state,[Chat,Socket])=>{
        state.Chat=Chat
        state.Socket = Socket
     },
     //设置导航状态 1:消息 2:联系人 3:群聊 4:星球
     SETNAVI:(state,index) => state.NaviState = index ,

     //设置内容状态 0:空状态 1:消息 2:联系人 
     SETCONTENT:(state,[index,title]) =>{
        state.ContentState =index
        state.ContentTitle=title
     },
    //设置抽屉状态 0:无 1:好友资料
     SETDRAWER:(state,[index,data]) => {
        state.DrawerState =index 
        state.DrawerData=data
     },
     



     //设置当前聊天的对象
     SETCHATNOW:(state,data) =>{
       let ChatNow=state.Chatlist.find(item => item.touid == data.touid)
       if(ChatNow == null){ //把该联系人插入聊天列表
          state.Chatlist.push(data)   
          localStorage.setItem(`Chatlist:${data.uid}`,JSON.stringify(state.Chatlist)) 
          state.ChatNow = data
       }else {
          state.ChatNow = ChatNow
          ChatNow.unread = 0
       }

       //获取当前聊天对象的聊天内容
       state.ChatContentNow = JSON.parse(localStorage.getItem(`ChatContent:${data.uid} -> ${data.touid}`)) || []
     },
     //设置聊天列表 开始加载聊天列表
     SETCHATLIST(state,uid){
        state.Chatlist =JSON.parse(localStorage.getItem(`Chatlist:${uid}`)) || []
     },
     
     //增加聊天内容
     ADDCHATCONTENT(state,data){
    
    
       let Chatlist = state.Chatlist.find(item => item.touid == data.touid)

       if( Chatlist == null){ //新增聊天列表内容
          let {id,uid,touid,username,headphoto,remark,content,deleted,top} =data
          let lasttime= data.createdtime
          Chatlist ={id,uid,touid,username,headphoto,remark,content,deleted,lasttime,top}
          state.Chatlist.push(Chatlist)
       }

       //设置最近的内容和时间 未读数量 更新聊天列表
       Chatlist.content=data.oldContent
       Chatlist.lasttime=data.createdtime

       if(data.flag == 2 || data.flag == 4){ //表示收到消息
          Chatlist.unread += 1
          if(state.ChatNow.touid == data.touid) //当前正在聊天
           Chatlist.unread = 0
       }
       if(data.flag == 3 || data.flag == 4){ //更新上一次 带有显示时间的聊天记录 的时间
          Chatlist.beforetime=data.createdtime
       }
       localStorage.setItem(`Chatlist:${data.uid}`,JSON.stringify(state.Chatlist)) 

       
       //更新聊天的内容
       state.ChatContentNow = JSON.parse(localStorage.getItem(`ChatContent:${data.uid} -> ${data.touid}`)) || []
       state.ChatContentNow.push(data)
       localStorage.setItem(`ChatContent:${data.uid} -> ${data.touid}`,JSON.stringify(state.ChatContentNow))
     },
  
     //删除正在聊天对象的全部聊天内容
     DELETEALLCHATCONTENT(state,data){
         state.ChatContentNow = []
         localStorage.removeItem(`ChatContent:${data.uid} -> ${data.touid}`)
         
         //修改对应的聊天列表内容
         let index = state.Chatlist.findIndex(item => item.touid == data.touid)
         state.Chatlist[index].lasttime=null
         state.Chatlist[index].content=null
         state.Chatlist[index].beforetime=null
         localStorage.setItem(`Chatlist:${data.uid}`,JSON.stringify(state.Chatlist)) 
     },
     //删除列表
     DELETECHATLIST(state,data){
         let index = state.Chatlist.findIndex(item => item.touid == data.touid)
         state.Chatlist.splice(index,1)
         localStorage.setItem(`Chatlist:${data.uid}`,JSON.stringify(state.Chatlist)) 
     },
     //修改列表
     EDITCHATLIST(state,data){
       state.Chatlist.forEach(element => {
         if(element.touid == data.touid) 
         Object.assign(element,data)
       })
       localStorage.setItem(`Chatlist:${data.uid}`,JSON.stringify(state.Chatlist)) 
     },
     //暂时添加 发送成功后再替换为永久的存储
     SETCHATCONTENTNOW:(state,data) => state.ChatContentNow.push(data)
  },
  actions:{
    CreateSocket(context,data){ //创建一个websocket服务
        let Chat = new ChatSocket(data)
        let Socket = Chat.Socket
        context.commit('SETCHAT',[Chat,Socket])
        context.commit('SETCHATLIST',data.uid)
    },
    async SendMessage(context,data){ //发送消息
      let Socket = context.state.Socket
      let touid = data.touid || 0
      let content = JSON.stringify(Object.assign({},data))
      let type = 1

      //本地发消息
      let newData =Object.assign({},data)
      newData.content = Common.initContent(newData.content) //内容进行解析 表情/换行


      context.commit('SETCHATCONTENTNOW',newData) //暂时添加

      data.id=null
      try{
        //存数据库
        let res = await request.post("/api/message/add",data)
        if(res.data.code == 200)
         {
           newData.state=1 //成功发送
           let sendContent =JSON.stringify(Object.assign({},res.data.data.tomessage))
           //WebSocket发给好友
           if(Socket) Socket.send(JSON.stringify({touid,type,content:sendContent}))

         }else {
            newData.state=2 //发送失败
            newData.faileReason = res.data.message
         }
         if(res.data?.data?.message)
         {
           
           res.data.data.message.oldContent =  res.data.data.message.content
           res.data.data.message.content =  Common.initContent(res.data?.data?.message?.content)
           context.commit('ADDCHATCONTENT',res.data?.data?.message)
         }
         return res.data
     }catch(error) {
        newData.state=2
        context.commit('ADDCHATCONTENT',newData)
        return {code:400,message:error}
    }

    },
   async ApplyFriend(context,data){ //申请好友请求
      let Socket = context.state.Socket
      let touid = data.touid || 0
      let content = JSON.stringify(Object.assign({},data))
      let type = 2
      try{
         let res = await request.post("/api/friendRecord/apply",data)
         if(res.data.code == 200)
          {
            if(res.data.data.state == 1)   //双方都申请直接同意
            await context.dispatch('ResolveFriendApply',res.data.data.FriendRecord)
            else if(Socket) Socket.send(JSON.stringify({touid,type,content}))  
          }
          return res.data
      }catch(error){return {code:400,message:error}}
    },

    async DeleteFriend(context,{uid,touid}){ //删除好友
    
      try{
         let res = await request.get("/api/friend/delete",{params:{uid,touid}})
         if(res.data.code == 200)
          {
              //删除好友信息
              await store.dispatch('Inform/refreshFriends',uid) //刷新好友
          }
          return res.data
      }catch(error){return {code:400,message:error}}
    },

   async ResolveFriendApply(context,data){ //同意或者拒绝好友请求
    let Socket = context.state.Socket
    let touid = data.uid || 0
    let content = JSON.stringify(Object.assign({},data))
    let type = 3

    try{
       let res = await request.post("/api/friendRecord/resolve",data)
       if(res.data.code == 200)
        {
          await store.dispatch('Inform/refreshFriendRecord',data.touid) //刷新申请记录
          if(data.type == 2) //同意好友申请
          await store.dispatch('Inform/refreshFriends',data.touid) //刷新好友
          
          if(Socket) Socket.send(JSON.stringify({touid,type,content})) //发消息
          
        }
        return res.data
    }catch(error){return {code:400,message:error}}
   },
   
    
   ///
  },
})